/**
 * Copyright 2005 SIB Framework

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.sibframework.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;


public class CryptoTool {
	
	//single crypto instance
	public final static int mask = 2;
	
	public byte[] SingleCrypto(byte[] bs) {
		for (int i=0; i < bs.length; i += mask) {
			bs[i] =  (byte) (~bs[i]);
			//bs[i] =  (byte) (Byte.MAX_VALUE - bs[i]);
		}
		return bs;
	}
	public byte[] SingleDecrypto(byte[] bs) {
		for (int i=0; i < bs.length; i += mask) {
			bs[i] =  (byte) (~bs[i]);
			//bs[i] =  (byte) (Byte.MAX_VALUE - bs[i]);
		}
		return bs;
	}
	
	//static part for advance crypto instance
	
    private static PBEKeySpec pbeKeySpec;
    private static PBEParameterSpec pbeParamSpec;
    private static SecretKeyFactory keyFac;

    // Salt
    private static byte[] salt = {
    	(byte)0xa9, (byte)0xe2, (byte)0xfe, (byte)0xcb,
        (byte)0x47, (byte)0x2e, (byte)0xd3, (byte)0x85
    };

    // Iteration count
    private static int count = 20;

    
    
	 public static Cipher getPBEncryptCipher(String password) {

		if (password == null) {
			new NullPointerException("Password can't be null.");
		}
		
		try {
			// Create a PBE parameter set
			pbeParamSpec = new PBEParameterSpec(salt, count);

			pbeKeySpec = new PBEKeySpec(password.toCharArray());
			keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
			SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

			// Create Cipher
			Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

			// Initialize Cipher with key and parameters
			pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

			return pbeCipher;

		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		return null;
	 }
	 
	 public static Cipher getPBDecryptCipher(String password) {

			if (password == null) {
				new NullPointerException("Password can't be null.");
			}
			
			try {
				// Create a PBE parameter set
				pbeParamSpec = new PBEParameterSpec(salt, count);
				keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

				//get key base password
				pbeKeySpec = new PBEKeySpec(password.toCharArray());
				SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

				// Create Cipher
				Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

				// Initialize Cipher with key and parameters
				pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

				return pbeCipher;

			} catch (InvalidKeyException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			} catch (InvalidAlgorithmParameterException e) {
				e.printStackTrace();
			}
			return null;
		 }
	 
	 
	 
	 /**
	  * test method
	  */
	 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String password = "abc";
		String source = "�Ұ������찲�ţ��찲����̫���� Simple is the best. Programmes de publicit��. ������ȫ�夫��";
		byte[] sbs = null;
		try {
			sbs = source.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		Cipher cipher = CryptoTool.getPBEncryptCipher(password);
		Cipher decipher = CryptoTool.getPBDecryptCipher(password);
		
		try {
			
			byte[] ps = cipher.doFinal(sbs);
			String es = new String(ps, "UTF-8");
			byte[] bps = decipher.doFinal(ps);
			String back = new String(bps, "UTF-8");

			System.out.println(source);
			System.out.println();
			System.out.println(es);
			System.out.println();
			System.out.println(back);
			
			//test stream api
			ByteArrayInputStream bais = new ByteArrayInputStream(sbs);
			CipherInputStream cis = new CipherInputStream(bais, cipher);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			CipherOutputStream cos = new CipherOutputStream(baos, decipher);
			byte[] mb = new byte[8];
			while (cis.available() > 0) {
				cis.read(mb);
				cos.write(mb);
			}
			back = new String(baos.toByteArray(), "UTF-8");
			System.out.println(back);
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
